//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.kun.portal.webframe.controller;

import com.kun.framework.core.util.DateUtils;
import com.kun.framework.crypto.cipher.DesCipher;
import com.kun.framework.web.web.vo.ValueLabelVo;
import com.kun.portal.webframe.dao.FwTeamDao;
import com.kun.portal.webframe.exception.FwBaseException;
import com.kun.portal.webframe.po.FwRolePo;
import com.kun.portal.webframe.po.FwTeamPo;
import com.kun.portal.webframe.po.FwUserPo;
import com.kun.portal.webframe.service.FwRoleService;
import com.kun.portal.webframe.service.FwTeamService;
import com.kun.portal.webframe.service.FwUserService;
import com.kun.portal.webframe.service.KunTraceLogService;
import com.kun.portal.webframe.util.FwBaseUtil;
import com.kun.portal.webframe.util.HeaderUtil;
import com.kun.portal.webframe.util.UserSessionUtil;
import com.kun.portal.webframe.vo.Teams;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.ResponseEntity.BodyBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping({"/api/webframe"})

public class FwTeamController {
    private static final Logger LOG = LoggerFactory.getLogger(FwTeamController.class);
    @Autowired
    private FwTeamService fwteamService;
    @Autowired
    private FwRoleService roleService;
    @Autowired
    private FwUserService userService;
    @Autowired
    private FwUserService fwUserService;
    @Autowired
    private FwTeamService fwTeamService;
    @Autowired
    private FwTeamDao fwTeamDao;
    @Autowired

    private KunTraceLogService kunTraceLogService;

    public FwTeamController() {
    }

    @RequestMapping(
            value = {"/fwteam"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FwTeamPo> findByTeamNameLike(@RequestParam(required = false) String key, Pageable pageable, HttpSession session) {
        key = key == null?"":key;
        FwUserPo user = UserSessionUtil.getCurrentUser(session);
        return this.fwteamService.findByCreatorAndTeamNameContaining(user.getUserId(), key, pageable);
    }

    @RequestMapping(
            value = {"/fwteam/queryAllTeams"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FwTeamPo> queryAll(Pageable pageable) {
        return this.fwTeamService.queryAll(pageable);
    }

    @RequestMapping(
            value = {"/fwteam/queryAllTeamsNopage"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public List<FwTeamPo> queryAll(@RequestParam(required =  false) Boolean all) {
        if(all==null){
             all =true;
        }
        List<FwTeamPo> list = this.fwTeamService.queryAll(all);
        Set<FwTeamPo> set =  new HashSet<>(list);
        return new ArrayList<FwTeamPo>(set);
    }





    @RequestMapping(
            value = {"/fwteam/teamsInfo"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map<String, Object> countTeamUser(HttpServletRequest request) {
        Map<String, Object> result = new HashMap();
        HttpSession currentSession = request.getSession();
        FwTeamPo currentTeam = UserSessionUtil.getCurrentUserTeam(currentSession);
        if(currentTeam != null) {
            String teamId = currentTeam.getTeamId();
            result = this.getResult(teamId, currentSession);
            ((Map)result).put("currentTeam", currentTeam);
            ((Map)result).put("status", Integer.valueOf(200));
            ((Map)result).put("msg", "success");
        } else {
            ((Map)result).put("status", Integer.valueOf(400));
            ((Map)result).put("msg", "该用户还未加入任何团队!");
        }

        return (Map)result;
    }

    @RequestMapping(
            value = {"/fwteams"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map<String, Object> fetchTeamChienld(HttpSession session) {
        FwTeamPo currentTeam = UserSessionUtil.getCurrentUserTeam(session);
        Map<String, Object> result = new HashMap();
        if(currentTeam != null) {
            String teamId = currentTeam.getTeamId();
            if(Teams.SysTeam.name().equals(teamId)) {
                teamId = "";
            }

            teamId = teamId + "%";
            List<FwTeamPo> teams = this.fwTeamService.findTeamAndChildren(teamId);
            result.put("teams", teams);
            result.put("status", Integer.valueOf(200));
            result.put("msg", "success");
        } else {
            result.put("status", Integer.valueOf(400));
            result.put("msg", "该用户还未加入任何团队!");
        }

        return result;
    }

    @RequestMapping(
            value = {"/fwteam/tree"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public Object fetchTeamChildren(@RequestParam(required = false) String teamId, HttpSession session) {
        teamId = StringUtils.isEmpty(teamId)?UserSessionUtil.getCurrentUserTeam(session).getTeamId():teamId;
        return this.fwTeamService.getTeamTree(teamId);
    }

    @RequestMapping(
            value = {"/fwteam/currentTeamChange"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map<String, Object> changeCurrentTeam(@RequestParam String teamId, HttpServletRequest request) {
        new HashMap();
        HttpSession currentSession = request.getSession();
        FwTeamPo currentTeam = this.fwTeamService.findByTeamId(teamId);
        UserSessionUtil.setCurrentTeam(currentSession, currentTeam);
        Map<String, Object> result = this.getResult(teamId, currentSession);
        result.put("currentTeam", currentTeam);
        return result;
    }

    private Map<String, Object> getResult(String teamId, HttpSession currentSession) {
        Map<String, Object> result = new HashMap();
        FwUserPo fwUserPo = UserSessionUtil.getCurrentUser(currentSession);
        //Set<FwTeamPo> teams = fwUserPo.getTeams();
        //teams = UserSessionUtil.getValidTeams(teams);
        List tabNum = new ArrayList();
        List procNum = new ArrayList();
        List<Object[]> resNum = new ArrayList();
        List<String> teamUsers = this.fwUserService.findFwUserByTeamId(teamId);
        //result.put("teams", teams);
        result.put("tabNum", tabNum);
        result.put("procNum", procNum);
        result.put("resNum", resNum);
        result.put("teamUserNum", Integer.valueOf(teamUsers.size()));
        return result;
    }

    @RequestMapping(
            value = {"/fwteam/check"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public List<FwTeamPo> findByFwUserUnique(@RequestBody Map<String, String> map, HttpSession session) {
        return this.fwteamService.findByFwTeamUnique(map);
    }

    @RequestMapping(
            value = {"/fwteam"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public ResponseEntity<FwTeamPo> addFwTeam(@RequestBody FwTeamPo fwteam, HttpSession session) {
        fwteam.setCreator(FwBaseUtil.getUserId(session));
        fwteam.setCreateTime(DateUtils.getNowDate());
        fwteam.setModifyTime(DateUtils.getNowDate());
        //fwteam.setTeamId(fwteam.getTeamCode());
//        if(!"1".equals(fwteam.getTeamLevel())) {
//            fwteam.setTeamId(fwteam.getParentCode() + "_" + fwteam.getTeamCode());
//        } else {
//
//        }

        FwTeamPo metaFwTeam = this.fwteamService.addFwTeam(fwteam);
        this.assignDefaultModule(metaFwTeam, session);
        return new ResponseEntity(metaFwTeam, HttpStatus.OK);
    }

       @RequestMapping(
            value = {"/fwteam"},
            method = {RequestMethod.PUT}
    )
    @ResponseBody
    public ResponseEntity<FwTeamPo> updateFwTeam(@RequestBody FwTeamPo fwteam, HttpSession session) {
        if(StringUtils.isEmpty(fwteam.getTeamId())) {
            return this.addFwTeam(fwteam, session);
        } else {
            FwTeamPo teamPo = this.fwteamService.findByTeamId(fwteam.getTeamId());
            fwteam.setRoleSet(teamPo.getRoleSet());
            if(fwteam.getUserList() == null) {
                fwteam.setUserList(teamPo.getUserList());
            }

            fwteam.setCreateTime(teamPo.getCreateTime());
            fwteam.setModifyTime(DateUtils.getNowDate());
            FwTeamPo metaFwTeam = this.fwteamService.updateFwTeam(fwteam);
            this.roleService.updateFwRoleUserByTeam(fwteam.getTeamId());
            return new ResponseEntity(metaFwTeam, HttpStatus.OK);
        }
    }

    @RequestMapping(
            value = {"/fwteamUser"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    @Transactional
    public ResponseEntity<FwTeamPo> updateFwTeamUser(@RequestBody FwTeamPo fwteam, HttpSession session)throws Exception  {
        if(StringUtils.isEmpty(fwteam.getTeamId())) {
            return this.addFwTeam(fwteam, session);
        } else {
            FwTeamPo teamPo = this.fwteamService.findByTeamId(fwteam.getTeamId());
            fwteam.setRoleSet(teamPo.getRoleSet());
            if(fwteam.getUserList() == null) {
                fwteam.setUserList(teamPo.getUserList());
            }
            FwUserPo fwUserPo = null ;
            for(FwUserPo user : fwteam.getUserList()){
                if(user.getUserId()==null||"".equals(user.getUserId())){
                  fwUserPo = user;
                  fwteam.getUserList().remove(user);
                  break;
                }
            }
            if(fwUserPo!=null){

                    FwUserPo user = UserSessionUtil.getCurrentUser(session);
                    fwUserPo.setCreator(user.getUserId());
                    fwUserPo.setCreateTime(DateUtils.getNowDate());
                    fwUserPo.setModifyTime(DateUtils.getNowDate());
                    fwUserPo.setUserPwd(DesCipher.encrypt(fwUserPo.getNewPwd()));
                    fwUserPo = fwUserService.updateFwUser(fwUserPo);
            }
            fwteam.getUserList().add(fwUserPo);
            fwteam.setCreateTime(teamPo.getCreateTime());
            fwteam.setModifyTime(DateUtils.getNowDate());
            FwTeamPo metaFwTeam = this.fwteamService.updateFwTeam(fwteam);
            this.roleService.updateFwRoleUserByTeam(fwteam.getTeamId());
            return new ResponseEntity(fwUserPo, HttpStatus.OK);
        }
    }




    @RequestMapping(
            value = {"/fwteam/status"},
            method = {RequestMethod.PUT}
    )
    @ResponseBody
    public ResponseEntity<FwTeamPo> updateFwTeamStatus(@RequestBody FwTeamPo fwteam, HttpSession session) {
        if(StringUtils.isEmpty(fwteam.getTeamId())) {
            throw new FwBaseException("请选择团队");
        } else {
            FwTeamPo teamPo = this.fwteamService.findByTeamId(fwteam.getTeamId());
            teamPo.setTeamStatus(fwteam.getTeamStatus());
            FwTeamPo metaFwTeam = this.fwteamService.updateFwTeam(teamPo);
            return new ResponseEntity(metaFwTeam, HttpStatus.OK);
        }
    }

    @RequestMapping(
            value = {"/fwteam/{teamId}"},
            method = {RequestMethod.DELETE}
    )
    @ResponseBody
    public ResponseEntity<Void> deleteFwTeam(@PathVariable("teamId") String teamId) {
        this.fwteamService.deleteFwTeam(teamId);
        return ((BodyBuilder)ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("fwteam", teamId))).build();
    }

    @RequestMapping(
            value = {"/fwteam/role"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FwRolePo> findRoleByTeamId(Pageable pageable, HttpSession session, @RequestParam(required = false,defaultValue = "") String key, @RequestParam(required = false) String teamId) {
        teamId = StringUtils.isEmpty(teamId)?FwBaseUtil.getTeamId(session):teamId;
        return Teams.AllTeam.name().equals(teamId)?this.roleService.queryAll(key, pageable):this.roleService.findRoleByTeamIdLikeAndKeyLike(teamId, key, pageable);
    }

    @RequestMapping(
            value = {"/fwteam/user"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FwUserPo> findUserByTeamId(Pageable pageable, HttpSession session, @RequestParam(required = false,defaultValue = "") String key, @RequestParam(required = false,defaultValue = "") String teamId) {
        teamId = StringUtils.isEmpty(teamId)?FwBaseUtil.getTeamId(session):teamId;
        if(Teams.AllTeam.name().equals(teamId)) {
            return this.userService.findAll("%" + key + "%", pageable);
        } else {
            FwTeamPo fwTeam = this.fwteamService.findByTeamId(teamId);
            Set<FwTeamPo> teams = new HashSet();
            teams.add(fwTeam);
            return this.userService.findFwUserByTeamsAndUserNameLike(teams, "%" + key + "%", pageable);
        }
    }

    @RequestMapping(
            value = {"/fwteamUserRole/user"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map<String, Object> fetchTeamUserRoles(@RequestParam String teamId, @RequestParam String key, HttpSession session) {
        FwTeamPo fwTeam = UserSessionUtil.getCurrentUserTeam(session);
        String currentlevel = fwTeam.getTeamLevel();
        List teamRoles = this.fwteamService.findTeamRole(teamId, currentlevel);
        List userRoles = this.fwteamService.findTeamUserRole(teamId, key);
        Map<String, Object> mp = new HashMap();
        mp.put("userRoles", userRoles);
        mp.put("teamRoles", teamRoles);
        return mp;
    }

    @RequestMapping(
            value = {"/fwteam/user/{teamId}"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Page<FwUserPo> findUserByTeamId(@PathVariable("teamId") String teamId, Pageable pageable) {
        return null;
    }

    @RequestMapping(
            value = {"/fwteam/user/{userId}"},
            method = {RequestMethod.DELETE}
    )
    @ResponseBody
    public ResponseEntity<Void> deleteFwUser(@PathVariable("userId") String userId) {
        this.userService.deleteFwUser(userId);
        return ((BodyBuilder)ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("fwuser", userId))).build();
    }

    @RequestMapping(
            value = {"/fwteam/user/{userId}/{teamId}"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map deleteTeamUser(@PathVariable("userId") String userId, @PathVariable("teamId") String teamId) {
        this.fwteamService.deleteTeamUsers(teamId, userId);
        Map<String, String> res = new HashMap();
        res.put("message", "ok");
        return res;
    }

    @RequestMapping(
            value = {"/fwteam/transferByUser/{userId}"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map queryByUserId(@PathVariable("userId") String userId, HttpSession session) {
        Map result = new HashMap();
        FwUserPo user = UserSessionUtil.getCurrentUser(session);
        List<ValueLabelVo> allcreated = this.fwteamService.findFwTeamByCreator(user.getUserId());
        List<String> selected = this.fwteamService.findFwTeamByUserId(userId);
        result.put("dataTeams", allcreated);
        result.put("myTeams", selected);
        return result;
    }

    @RequestMapping(
            value = {"/fwteam/transferByRole/{roleId}"},
            method = {RequestMethod.GET},
            produces = {"application/json"}
    )
    @ResponseBody
    public Map queryByRoleId(@PathVariable("roleId") String roleId, HttpSession session) {
        Map result = new HashMap();
        FwUserPo user = UserSessionUtil.getCurrentUser(session);
        List<ValueLabelVo> allcreated = this.fwteamService.findFwTeamByCreator(user.getUserId());
        List<String> selected = this.fwteamService.findFwTeamByRoleId(roleId);
        result.put("dataTeams", allcreated);
        result.put("myTeams", selected);
        return result;
    }

    @RequestMapping(
            value = {"/fwteam/updateFwTeamUserByTeamId"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public void updateFwTeamUserByTeamId(@RequestBody Map map, HttpSession session) {
        String teamId = (String)map.get("teamId");
        if(StringUtils.isEmpty(teamId) || Teams.CurrentTeam.name().equals(teamId)) {
            teamId = FwBaseUtil.getTeamId(session);
        }

        List<Map<String, String>> list = (List)map.get("userList");
        List<FwUserPo> userList = new ArrayList();
        Iterator var7 = list.iterator();

        while(var7.hasNext()) {
            Map<String, String> user = (Map)var7.next();
            FwUserPo userPo = new FwUserPo();
            userPo.setUserId((String)user.get("userId"));
            userList.add(userPo);
        }

        this.fwteamService.updateFwTeamUserByTeamId(teamId, userList);
    }

    @RequestMapping(
            value = {"/fwteam/updateFwTeamDuty"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public void updateFwTeamDuty(@RequestBody FwTeamPo fwTeam, HttpSession session) {
        this.fwTeamDao.save(fwTeam);
    }


    @RequestMapping(
            value = {"/fwteam/updateFwTeamUserByUserId"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public Map updateFwRoleUserByUserId(@RequestBody Map map, HttpSession session) {
        List<String> teamIds = (List)map.get("teamIds");
        String userId = (String)map.get("userId");
        this.fwteamService.updateFwTeamUserByUserId(teamIds, userId);
        return null;
    }

    @RequestMapping(
            value = {"/fwteam/updateFwRoleTeamByTeamId"},
            method = {RequestMethod.POST}
    )
    @ResponseBody
    public Map updateFwRoleTeamByTeamId(@RequestBody Map map, HttpSession session) {
        List<String> roleIds = (List)map.get("roleIds");
        String teamId = (String)map.get("teamId");
        this.fwteamService.updateFwRoleTeamByTeamId(roleIds, teamId);
        return null;
    }

    @RequestMapping(
            value = {"/fwteam/detailList"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public List<Map<String, String>> findDetailList(HttpSession session) {
        return this.fwteamService.findDetailList(FwBaseUtil.getTeamId(session));
    }

    @RequestMapping(
            value = {"/fwteam/select/parent"},
            method = {RequestMethod.GET}
    )
    @ResponseBody
    public List<Map<String, String>> getParentTeam(HttpSession session) {
        if(Teams.SysTeam.name().equals(FwBaseUtil.getTeamId(session))) {
            return this.fwteamService.findTopTeamSelect();
        } else {
            FwTeamPo team = UserSessionUtil.getCurrentUserTeam(session);
            Map map = new HashMap();
            map.put("label", team.getTeamName());
            map.put("value", team.getTeamId());
            List list = new ArrayList();
            list.add(map);
            return list;
        }
    }

    public void assignDefaultRole(FwTeamPo teamPo, HttpSession session) {
        String userId = FwBaseUtil.getUserId(session);
        teamPo.addRole(new FwRolePo("Developer", "开发者角色", userId));
        teamPo.addRole(new FwRolePo("Maintainer", "维护者角色", userId));
        teamPo.addRole(new FwRolePo("TeamAdmin", "团队管理角色", userId));
    }

    private void assignDefaultModule(FwTeamPo metaFwTeam, HttpSession session) {
        List<String> DEVELOPER_MODULELIST = new ArrayList(Arrays.asList(new String[]{"1001", "1102", "1103", "123", "127", "204", "402", "403", "409", "410", "901", "902", "903"}));
        List<String> TEAMADMIN_MODULELIST = new ArrayList(Arrays.asList(new String[]{"100", "101", "102", "104", "105", "106", "1001", "1102", "1103", "123", "127", "2", "200", "201", "202", "204", "3", "301", "302", "303", "402", "403", "404", "405", "406", "407", "408", "409", "410", "901", "902", "903"}));
        List<String> MAINTAINER_MODULELIST = new ArrayList(Arrays.asList(new String[]{"100", "101", "102", "104", "105", "106", "204", "3", "301", "302", "303"}));
        Set<FwRolePo> roleSet = metaFwTeam.getRoleSet();
        Iterator var8 = roleSet.iterator();

        while(var8.hasNext()) {
            FwRolePo role = (FwRolePo)var8.next();
            if("Developer".equals(role.getRoleCode())) {
                this.roleService.saveTeamModule(role.getRoleId(), DEVELOPER_MODULELIST);
            } else if("TeamAdmin".equals(role.getRoleCode())) {
                this.roleService.saveTeamModule(role.getRoleId(), TEAMADMIN_MODULELIST);
            } else if("Maintainer".equals(role.getRoleCode())) {
                this.roleService.saveTeamModule(role.getRoleId(), MAINTAINER_MODULELIST);
            }
        }

    }
}
